<template>
	<view class="topic-detail-page">
		<!-- 1. 自定义导航栏 ( position: fixed ) -->
		<view class="custom-navbar" :class="{ 'is-sticky': isNavbarSticky }" v-show="isNavbarSticky"
			:style="{ paddingTop: statusBarHeight + 'px' }">
			<u-icon class="custom-navbar-icon" name="arrow-left" :color="isNavbarSticky?'#000':'#fff'" size="22"
				@click="goBack"></u-icon>
			<view class="nav-center">
				<view :style="{'color':isNavbarSticky?'#000':'#fff'}">热门话题</view>
			</view>
			<view class="nav-right-icons">
				<u-icon name="share-square" :color="isNavbarSticky?'#000':'#fff'" size="22"></u-icon>
				<u-icon name="more-dot-fill" :color="isNavbarSticky?'#000':'#fff'" size="22"
					customStyle="margin-left: 20rpx;"></u-icon>
			</view>
		</view>

		<!-- 2. 主滚动区域 -->
		<scroll-view scroll-y class="main-content" @scroll="handleScroll" @scrolltolower="loadMorePosts">
			<!-- 头部背景容器 -->
			<view class="header-wrapper">
				<image class="header-background-image" src="http://www.hacn86.cn/alley-food/wenlou.png"
					mode="aspectFill"></image>

				<!-- 话题头部信息 -->
				<view class="topic-header" v-if="topicInfo.title">
					<!-- 头部占位，防止内容被导航栏遮挡 -->
					<view :style="{ height: navBarHeight + 'px' }"></view>
					<view class="topic-title-section">
						<text class="indexIconFont hash icon-remehuati-jinghaojian">


							<text class="indexIconFont huobao icon-remenhuati-huobao"></text>
						</text>

						<h1 class="topic-title">{{ topicInfo.title }}</h1>
					</view>
				</view>
			</view>
			<view class="topic-content" v-if="topicInfo.title">
				<view class="topic-stats">
					<!-- 层叠头像 -->
					<view class="avatar-group-container">
						<u-avatar-group :urls="topicInfo.participantAvatars" size="24" gap="0.4"></u-avatar-group>
					</view>
					<text>{{ topicInfo.postCount }} 条帖子</text>
					<text class="dot">·</text>
					<text>{{ topicInfo.viewCount }} 浏览量</text>
				</view>
				<view class="topic-description">
					{{ topicInfo.description }}
				</view>
				<view class="topic-tags">
					<u-tag v-for="tag in topicInfo.relatedTags" :key="tag.text" :text="tag.text" shape="circle"
						bgColor="#EDEBEC" borderColor="#EDEBEC" color="#000000" size="mini" :icon="tag.icon"></u-tag>
				</view>
			</view>

			<!-- 筛选Tabs和搜索框 -->
			<view class="filter-tabs-container">
				<view class="custom-tabs">
					<view v-for="(tab, index) in tabs" :key="index" class="tab-item"
						:class="{ active: currentTab === index }" @click="changeTab(index)">
						{{ tab.name }}
					</view>
				</view>
				<view class="search-wrapper">
					<u-search placeholder="试一试搜话题..." :showAction="false" height="30" bgColor="#FFFFFF"></u-search>
				</view>
			</view>

			<!-- 帖子列表 -->
			<view class="post-list">
				<view v-if="postList.length === 0 && postsLoadingStatus === 'nomore'" class="empty-state">
					<u-empty mode="data" text="暂无相关帖子"></u-empty>
				</view>

				<view class="post-item" v-for="post in postList" :key="post.id">
					<!-- 用户信息 -->
					<view class="post-author">
						<view class="author-left">
							<u-avatar :src="post.author.avatar" size="34"></u-avatar>
							<text class="author-name">{{ post.author.name }}</text>
						</view>
						<text class="reply-time">回复于{{ formatTimeAgo(post.replyTime) }}</text>
					</view>

					<!-- 内容区域 -->
					<view
						:class="post.images.length === 1 ? 'post-content single-image-layout' : 'post-content multi-image-layout'">
						<view class="post-text-content">
							<!-- 新增：帖子标题 -->
							<view class="post-title">{{ post.title }}</view>
							<!-- post-shrink现在只包裹内容 -->
							<view class="post-text">{{ post.content }}</view>

						</view>
						<!-- 新增：自定义图片展示区域，替换u-album -->
						<view class="post-media-content">
							<view class="image-grid" :class="[post.images.length > 1 ? 'multi' : 'single']">
								<view class="image-wrapper" v-for="(imgUrl, imgIndex) in post.images.slice(0, 3)"
									:key="imgIndex">
									<image :src="imgUrl" mode="aspectFill" class="post-image"></image>
								</view>
							</view>
						</view>
					</view>

					<common-post-actions :data="post"></common-post-actions>
				</view>

				<u-loadmore :status="postsLoadingStatus" />
			</view>
		</scroll-view>
		<!-- 底部悬浮的“参与话题”按钮 -->
		<view class="participate-button-container">
			<view class="participate-button" @click="navigateToParticipate">
				<u-icon name="/static/index/featured/icon_cyht.png" color="#fff" size="20"></u-icon>
				<!-- <text class="indexIconFont icon-canyuhuati-qianbi"></text> -->
				<text class="button-text">参与话题</text>
			</view>
		</view>
	</view>
</template>

<script>
	import commonPostActions from '@/components/common-post-actions/common-post-actions.vue';
	import postShrink from '@/components/post-shrink/post-shrink.vue';

	export default {
		components: {
			commonPostActions,
			postShrink
		},
		data() {
			return {
				statusBarHeight: 0,
				navBarHeight: 0,
				isNavbarSticky: false, // 控制导航栏背景
				topicInfo: {},
				tabs: [{
					name: '默认'
				}, {
					name: '最新'
				}],
				currentTab: 0,
				postList: [],
				postsLoadingStatus: 'loadmore',
				page: 1,
				pageSize: 5,
			};
		},
		onLoad() {
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight;
			// this.navBarHeight = systemInfo.statusBarHeight + 44;
			this.navBarHeight = systemInfo.statusBarHeight + 120;

			const eventChannel = this.getOpenerEventChannel();
			if (eventChannel && eventChannel.on) {
				eventChannel.on('acceptDataFromCirclePage', ({
					item
				}) => {
					this.topicInfo = {
						title: item.title,
						postCount: '265',
						viewCount: '20.4万',
						participantAvatars: [
							'https://picsum.photos/seed/avatar1/100/100',
							'https://picsum.photos/seed/avatar2/100/100',
							'https://picsum.photos/seed/avatar3/100/100',
							'https://picsum.photos/seed/avatar4/100/100'
						],
						description: '人们爱用镜头记录生活，每一张照片背后或许都有难忘的回忆。不过，记忆会被时间冲淡，可镜头会为你留存美好~',
						relatedTags: [{
								text: '老照片',
								icon: '/static/release/icon_ht.png'
							},
							{
								text: '50年前的老淮安',
								icon: '/static/release/icon_ht.png'
							},
							{
								text: '回忆杀',
								icon: '/static/release/icon_ht.png'
							}
						],
					};
					this.loadPosts(true);
				});
			}
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},
			handleScroll(e) {
				this.isNavbarSticky = e.detail.scrollTop > 30;
			},
			changeTab(index) {
				this.currentTab = index;
				this.loadPosts(true);
			},
			loadMorePosts() {
				this.loadPosts(false);
			},
			loadPosts(isRefresh = false) {
				if (isRefresh) {
					this.page = 1;
					this.postList = [];
					this.postsLoadingStatus = 'loadmore';
				}
				if (this.postsLoadingStatus === 'nomore' || this.postsLoadingStatus === 'loading') {
					return;
				}
				this.postsLoadingStatus = 'loading';

				setTimeout(() => {
					const newPosts = this.generateMockPosts(this.pageSize);
					this.postList = [...this.postList, ...newPosts];

					if (newPosts.length < this.pageSize || this.page >= 3) {
						this.postsLoadingStatus = 'nomore';
					} else {
						this.postsLoadingStatus = 'loadmore';
						this.page++;
					}
				}, 800);
			},
			generateMockPosts(count) {
				const posts = [];
				const now = Date.now();
				for (let i = 0; i < count; i++) {
					const imageCount = Math.random() < 0.4 ? 1 : Math.floor(Math.random() * 8) + 2;
					posts.push({
						id: `${this.page}-${i}`,
						author: {
							avatar: `https://picsum.photos/seed/${now + i}/100/100`,
							name: ['老淮安探索家', '一只小美美', '爱吃洛洛米的小C', '大花洒的意愿'][Math.floor(Math.random() * 4)],
						},
						replyTime: now - Math.floor(Math.random() * 36000000),
						title: '回顾30年前的老淮安',
						content: imageCount === 1 ?
							'我手机里有几张旧照片，大家可以猜猜是哪里，有些照片是10多年前拍下的，如今很多人应该已经不知道这里是哪里了。' :
							'1995年淮安有很多代表性建筑，可是随着时代的变迁已经被拆除了...',
						images: Array.from({
							length: imageCount
						}, (_, j) => `https://picsum.photos/seed/${now + i + j}/400/300`),
						likeCount: Math.floor(Math.random() * 1000),
						isLiked: Math.random() > 0.5 ? 1 : 0,
						commentCount: Math.floor(Math.random() * 500),
						collectCount: Math.floor(Math.random() * 800),
						isCollected: Math.random() > 0.5 ? 1 : 0,
						repostCount: Math.floor(Math.random() * 100)
					});
				}
				return posts;
			},
			formatTimeAgo(timestamp) {
				const now = new Date().getTime();
				const diff = now - timestamp;
				const seconds = Math.floor(diff / 1000);
				const minutes = Math.floor(seconds / 60);
				const hours = Math.floor(minutes / 60);
				const days = Math.floor(hours / 24);

				if (minutes < 1) return '刚刚';
				if (minutes < 60) return `${minutes}分钟前`;
				if (hours < 24) return `${hours}小时前`;
				if (days < 7) return `${days}天前`;

				const date = new Date(timestamp);
				return `${date.getMonth() + 1}-${date.getDate()}`;
			},

			// 跳转到参与话题页面
			navigateToParticipate() {
				if (!this.topicInfo || !this.topicInfo.title) {
					uni.showToast({
						title: '话题信息加载中',
						icon: 'none'
					});
					return;
				}
				uni.navigateTo({
					url: '/pages_sub/index/topic-participate/topic-participate',
					success: (res) => {
						// 通过 eventChannel 向新页面传递话题数据
						res.eventChannel.emit('acceptDataFromTopicDetail', {
							topic: this.topicInfo
						});
					}
				});
			},
		}
	};
</script>

<style lang="scss" scoped>
	.topic-detail-page {
		background-color: #fff;
	}

	.custom-navbar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 999;
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 44px;
		padding: 0 30rpx;
		transition: background-color 0.3s ease;
		background-color: transparent;

		&.is-sticky {
			background-color: #fff;
			box-shadow: 0 8rpx 10rpx rgba(0, 0, 0, 0.06);
			// border-bottom: 1rpx solid #f0f0f0;
		}

		.nav-center {
			font-weight: 700;
		}

		.nav-right-icons {
			display: flex;
			align-items: center;
		}
	}

	.main-content {
		height: 100vh;
	}

	.header-wrapper {
		position: relative;

		.header-background-image {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			z-index: 1;
		}

		.topic-header {
			position: relative;
			z-index: 2;
			padding: 30rpx;
			color: #fff;
			background-color: rgba(0, 0, 0, 0.3);

			.topic-title-section {
				display: flex;

				.hash {
					position: relative;
					width: 60rpx;
					height: 60rpx;
					line-height: 60rpx;
					padding-left: 14rpx;
					background-color: #fff;
					border-radius: 50%;
					font-size: 30rpx;
					font-weight: bold;
					color: #000;
					margin-right: 10rpx;

					.huobao {
						color: #F45917;
						position: absolute;
						bottom: -14rpx;
						font-size: 30rpx;
						right: 0rpx;
					}
				}

				.topic-title {
					font-size: 46rpx;
					font-weight: bold;
					color: #fff;
				}
			}
		}
	}

	.topic-content {
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #f0f0f0;

		.topic-stats {
			display: flex;
			align-items: center;
			font-size: 24rpx;
			color: #666;
			margin: 16rpx 0;

			.avatar-group-container {
				margin-right: 16rpx;
			}

			.dot {
				margin: 0 10rpx;
			}
		}

		.topic-description {
			font-size: 28rpx;
			color: #333;
			line-height: 1.6;
			margin-bottom: 24rpx;
		}

		.topic-tags {
			display: flex;
			gap: 16rpx;

			::v-deep .u-tag__icon {
				margin-right: 8rpx;
			}
		}
	}

	.filter-tabs-container {
		margin-top: 88rpx;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		height: 100rpx;
		background-color: #fff;

		.custom-tabs {
			display: flex;

			.tab-item {
				padding: 10rpx 20rpx;
				margin-right: 20rpx;
				font-size: 28rpx;
				color: #666;
				border-radius: 30rpx;
				background-color: #EDEBEC;
				transition: all 0.3s ease;

				&.active {
					background-color: #F5C94B;
					color: #000;
					font-weight: bold;
				}
			}
		}

		.search-wrapper {
			margin-left: auto;
			width: 300rpx;
		}
	}

	.post-list {

		.empty-state {
			padding: 100rpx 0;
		}
	}

	.post-item:first-child {
		border-start-end-radius: 30rpx;
		border-start-start-radius: 30rpx;
	}

	.post-item {
		padding: 30rpx 30rpx 10rpx 30rpx;
		border-bottom: 12rpx solid #f0f0f0;
		background-color: #fff;

		&:last-child {
			border-bottom: none;
		}

		.post-author {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 20rpx;

			.author-left {
				display: flex;
				align-items: center;

				.author-name {
					margin-left: 16rpx;
					font-size: 28rpx;
					color: #333;
				}
			}

			.reply-time {
				font-size: 24rpx;
				color: #999;
			}
		}

		.post-content {
			.post-text-content {
				.post-title {
					font-size: 35rpx;
					font-weight: 700;
					color: #000;
					margin-bottom: 10rpx;
					// --- 标题多行省略 ---
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-line-clamp: 2; // 限制为两行
					-webkit-box-orient: vertical;
					white-space: normal;
				}

				.post-text {
					font-size: 28rpx;
					color: #666;
					margin-top: 20rpx;
					// --- 内容多行省略 ---
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-line-clamp: 2; // 限制为三行
					-webkit-box-orient: vertical;
					white-space: normal;
				}
			}

			&.multi-image-layout .post-text-content {
				margin-bottom: 20rpx;
			}

			&.single-image-layout {
				display: flex;
				gap: 20rpx;

				.post-text-content {
					flex: 1;
					min-width: 0;
				}

				.post-media-content {
					flex-shrink: 0;
				}
			}

			.post-media-content {
				.image-grid {
					display: flex;
					gap: 10rpx;

					&.multi {
						flex-wrap: wrap;

						.image-wrapper {
							width: 220rpx;
							height: 150rpx;
						}
					}

					&.single {
						.image-wrapper {
							width: 260rpx;
							height: 180rpx;
						}
					}

					.image-wrapper {
						.post-image {
							width: 100%;
							height: 100%;
							border-radius: 30rpx;
							background-color: #f0f0f0;
						}
					}
				}
			}
		}
	}

	/* 底部悬浮按钮样式 */
	.participate-button-container {
		position: fixed;
		bottom: 100rpx; // 距离底部距离，可根据tabbar调整
		left: 50%;
		transform: translateX(-50%);
		z-index: 990;

		.participate-button {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 20rpx 30rpx;
			background-color: #000000;
			color: #fff;
			border-radius: 50rpx;
			box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.2);

			.button-text {
				font-size: 30rpx;
				margin-left: 12rpx;
				/* 设置背景渐变 */
				background: linear-gradient(to bottom, #ffde06, #68ff0a);
				/* 限制背景只显示文字区域 */
				-webkit-background-clip: text;
				background-clip: text;
				/* 确保文字颜色透明，使背景色显示 */
				color: transparent;
				font-weight: bold;
			}
		}
	}
</style>